package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Id    int    `json:"id"`
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Class string `json:"class"`
}

func NewStudent(id int, name string, age int, class string) *Student {
	return &Student{Id: id, Name: name, Age: age, Class: class}
}

type StudentClass struct {
	stuList []*Student //切片
}

func NewStudentClass() *StudentClass {
	return &StudentClass{stuList: make([]*Student, 0, 100)}
}
func (s *StudentClass) addStudent(stu *Student) {
	s.stuList = append(s.stuList, stu)
	fmt.Println("添加学生成功！")
}

//判断学生的学号是否存在
//func (s *StudentClass) stuIdIsExists(id int) bool {
//	existsFlag := false
//	for _, value := range s.stuList {
//		if value.Id == id {
//			existsFlag = true
//		}
//	}
//	return existsFlag
//}
func (s *StudentClass) stuIdIsExists(id int) (existsFlag bool) {
	//existsFlag := false
	for _, value := range s.stuList {
		if value.Id == id {
			existsFlag = true
		}
	}
	return
}
func (s *StudentClass) updateStudent(stu *Student) {
	for i, student := range s.stuList {
		if student.Id == stu.Id {
			s.stuList[i] = stu
			fmt.Printf("ID:%v,更新成功\n", stu.Id)
			break
		}
	}
}
func (s *StudentClass) deleteStudent(id int) {
	for i, student := range s.stuList {
		if student.Id == id {
			s.stuList = append(s.stuList[:i], s.stuList[i+1:]...)
			fmt.Printf("ID:%v,删除成功\n", id)
			break
		}
	}
}
func (s *StudentClass) displayStudent(id int) {
	for i, student := range s.stuList {
		if student.Id == id {
			j, err := json.Marshal(s.stuList[i])
			if err != nil {
				fmt.Printf("%v\n", err)
				break
			}
			fmt.Println(string(j))
			break
		}
	}
}
func main() {
	stuList := NewStudentClass()
	stuList.addStudent(NewStudent(1, "stu1", 11, "2022计算机1"))
	stuList.addStudent(NewStudent(2, "stu2", 12, "2022计算机1"))
	stuList.addStudent(NewStudent(3, "stu3", 10, "2022计算机2"))
	stuList.addStudent(NewStudent(4, "stu4", 9, "2022计算机2"))
	stuList.addStudent(NewStudent(5, "stu5", 12, "2022计算机3"))
	fmt.Println("---------------------------------------")
	for _, value := range stuList.stuList {
		j, err := json.Marshal(value)
		if err != nil {
			fmt.Printf("%v\n", err)
		}
		fmt.Println(string(j))
	}
	fmt.Println("---------------------------------------")
	stuList.updateStudent(NewStudent(2, "stu2", 13, "2022计算机1"))
	fmt.Println("---------------------------------------")
	id := 13
	if stuList.stuIdIsExists(id) {
		fmt.Printf("找到了编号为\"%v\"的同学\n", id)
	} else {
		fmt.Printf("未能找到编号为\"%v\"的同学\n", id)
	}
	fmt.Println("---------------------------------------")
	stuList.displayStudent(2)
	fmt.Println("---------------------------------------")
	stuList.deleteStudent(3)
	fmt.Println("---------------------------------------")
	for _, value := range stuList.stuList {
		j, err := json.Marshal(value)
		if err != nil {
			fmt.Printf("%v\n", err)
		}
		fmt.Println(string(j))
	}

}
